// dr.C -- drift distance distribution for dcs around target

void a(vector<TH1 *> &v, TH1 *h){ v.push_back(h); }
void dr(){
  TFile *f = new TFile(getenv("TMP1"), "UPDATE");
  TTree *etf = (TTree *)f->Get("etf");
  vector<TH1 *> v;
  TH1 *h0;
  char zcut[64] = "";
  static const int Z = 29;
  if(Z > 0) sprintf(zcut, "az0>%.2f && az0<%.2f", Z-0.5, Z+0.5);

  const char ud[2] = {'U', 'D'}, xy[2] = {'X', 'Y'};
  char hname[64]{}, layer[64]{};
  const double rg[2][2] = {{-0.5, 3.}, {-1., 6.}};
  for(int i = 0; i < 2; i++){ // loop over U, D
    for(int j = 0; j < 2; j++){ // loop over 0, 1
      for(int k = 0; k < 2; k++){ // loop over X, Y
        for(int l = 0; l < 2; l++){ // loop over X0, 1
          sprintf(layer, "dcTa%c%d%c%d", ud[i], j, xy[k], l);
          sprintf(hname, "h%s", layer);
          h0 = new TH1F(hname, Form("Drift Distance of %s", layer), 200, rg[i][0], rg[i][1]);
          h0->GetXaxis()->SetTitle("Drift Distance [mm]");
          etf->Project(hname, Form("%s.GetR()", layer), Form("%s && %s.fired()>=2", zcut, layer));
          a(v, h0);
          cout << "Processing " << layer << ": " << zcut << "...\r" << flush;
        } // end for over X1,2
      } // end for over X, Y
    } // end for over 1, 2
  } // end for over U, D
  cout << endl;

  TCanvas *c = new TCanvas("c", "1-D Drift Distance Distribution for post Mag dcs", 1680, 1050);
  c->Divide(2, 2);
  int id = 0;
  c->Print("dr.pdf[");
  for(int i = 0; i < 2; i++){ // U,D
    for(int j = 0; j < 2; j++){ // 0, 1
      for(int k = 0; k < 4; k++){ // X0, 1; Y0, 1
        c->cd(k+1); v[id++]->Draw();
      } // end for k
      c->Print("dr.pdf");
    } // end for over j
  } // end for over i
  c->Print("dr.pdf]");
} // end dr
